#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
代理主机查询对话框模块 - 用于查询代理下的所有主机
"""

import logging
import json
import os
import csv
from typing import Dict, List, Any, Optional
from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
    QLineEdit, QPushButton, QFormLayout, QDialogButtonBox,
    QComboBox, QSpinBox, QTabWidget, QWidget, QTextEdit,
    QCheckBox, QMessageBox, QTableWidget, QTableWidgetItem,
    QHeaderView, QGroupBox, QRadioButton, QProgressBar,
    QFileDialog
)
from PyQt5.QtCore import Qt, pyqtSlot, QThread, pyqtSignal
from PyQt5.QtGui import QFont

from src.zabbix_api import ZabbixAPI

logger = logging.getLogger(__name__)

class ProxyHostsDialog(QDialog):
    """代理主机查询对话框"""
    
    def __init__(self, api: ZabbixAPI, parent=None):
        """
        初始化代理主机查询对话框
        
        Args:
            api (ZabbixAPI): Zabbix API客户端
            parent: 父窗口
        """
        super().__init__(parent)
        self.api = api
        self.proxy_list = []
        self.hosts_data = []
        self.setup_ui()
        self.load_proxies()
    
    def setup_ui(self):
        """设置UI界面"""
        self.setWindowTitle("代理主机查询")
        self.resize(800, 600)
        self.setModal(True)
        
        # 创建主布局
        main_layout = QVBoxLayout(self)
        
        # 代理选择区域
        proxy_group = QGroupBox("选择代理")
        proxy_layout = QFormLayout(proxy_group)
        
        # 代理下拉框
        self.proxy_combo = QComboBox()
        self.proxy_combo.addItem("-- 请选择代理 --", "")
        self.proxy_combo.currentIndexChanged.connect(self.on_proxy_changed)
        proxy_layout.addRow("代理服务器:", self.proxy_combo)
        
        # 查询按钮
        self.query_btn = QPushButton("查询主机")
        self.query_btn.clicked.connect(self.on_query_hosts)
        proxy_layout.addRow("", self.query_btn)
        
        main_layout.addWidget(proxy_group)
        
        # 主机列表区域
        hosts_group = QGroupBox("主机列表")
        hosts_layout = QVBoxLayout(hosts_group)
        
        # 搜索区域
        search_layout = QHBoxLayout()
        
        self.search_edit = QLineEdit()
        self.search_edit.setPlaceholderText("搜索主机")
        self.search_edit.textChanged.connect(self.filter_hosts)
        search_layout.addWidget(self.search_edit)
        
        hosts_layout.addLayout(search_layout)
        
        # 主机表格
        self.hosts_table = QTableWidget(0, 5)
        self.hosts_table.setHorizontalHeaderLabels(["ID", "主机名", "可见名称", "状态", "可用性"])
        self.hosts_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.hosts_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.hosts_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.hosts_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        self.hosts_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
        self.hosts_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents)
        hosts_layout.addWidget(self.hosts_table)
        
        # 状态栏
        self.status_label = QLabel("就绪")
        hosts_layout.addWidget(self.status_label)
        
        main_layout.addWidget(hosts_group)
        
        # 导出按钮区域
        export_layout = QHBoxLayout()
        
        self.export_btn = QPushButton("导出到CSV")
        self.export_btn.clicked.connect(self.on_export)
        self.export_btn.setEnabled(False)
        export_layout.addWidget(self.export_btn)
        
        self.copy_btn = QPushButton("复制主机名称")
        self.copy_btn.clicked.connect(self.on_copy_hostnames)
        self.copy_btn.setEnabled(False)
        export_layout.addWidget(self.copy_btn)
        
        main_layout.addLayout(export_layout)
        
        # 添加关闭按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Close)
        button_box.rejected.connect(self.reject)
        main_layout.addWidget(button_box)
    
    def load_proxies(self):
        """加载代理列表"""
        try:
            # 获取所有代理
            proxies = self.api.get_proxies()
            self.proxy_list = proxies
            
            # 添加到下拉框
            self.proxy_combo.clear()
            self.proxy_combo.addItem("-- 请选择代理 --", "")
            
            for proxy in proxies:
                self.proxy_combo.addItem(proxy.get('host', ''), proxy.get('proxyid', ''))
            
            self.status_label.setText(f"已加载 {len(proxies)} 个代理")
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"加载代理列表失败: {str(e)}")
            logger.error(f"加载代理列表失败: {str(e)}")
    
    def on_proxy_changed(self, index):
        """代理选择变化处理"""
        # 清空主机表格
        self.hosts_table.setRowCount(0)
        self.hosts_data = []
        
        # 禁用导出按钮
        self.export_btn.setEnabled(False)
        self.copy_btn.setEnabled(False)
        
        # 更新状态
        if index > 0:
            proxy_name = self.proxy_combo.currentText()
            self.status_label.setText(f"已选择代理: {proxy_name}")
        else:
            self.status_label.setText("就绪")
    
    def on_query_hosts(self):
        """查询主机列表"""
        # 获取选中的代理ID
        proxy_id = self.proxy_combo.currentData()
        
        if not proxy_id:
            QMessageBox.warning(self, "警告", "请先选择一个代理服务器")
            return
        
        # 清空主机表格
        self.hosts_table.setRowCount(0)
        self.hosts_data = []
        
        try:
            # 更新状态
            proxy_name = self.proxy_combo.currentText()
            self.status_label.setText(f"正在查询代理 {proxy_name} 下的主机...")
            
            # 获取代理下的主机
            hosts = self.api.get_hosts_by_proxy(proxy_id)
            self.hosts_data = hosts
            
            # 添加到表格
            for i, host in enumerate(hosts):
                self.hosts_table.insertRow(i)
                
                # ID
                id_item = QTableWidgetItem(host.get('hostid', ''))
                id_item.setFlags(id_item.flags() & ~Qt.ItemIsEditable)
                self.hosts_table.setItem(i, 0, id_item)
                
                # 主机名
                host_item = QTableWidgetItem(host.get('host', ''))
                host_item.setFlags(host_item.flags() & ~Qt.ItemIsEditable)
                self.hosts_table.setItem(i, 1, host_item)
                
                # 可见名称
                name_item = QTableWidgetItem(host.get('name', ''))
                name_item.setFlags(name_item.flags() & ~Qt.ItemIsEditable)
                self.hosts_table.setItem(i, 2, name_item)
                
                # 状态
                status = "启用" if host.get('status', '1') == '0' else "禁用"
                status_item = QTableWidgetItem(status)
                status_item.setFlags(status_item.flags() & ~Qt.ItemIsEditable)
                self.hosts_table.setItem(i, 3, status_item)
                
                # 可用性
                available = host.get('available', '0')
                available_text = {
                    '0': '未知',
                    '1': '可用',
                    '2': '不可用'
                }.get(available, '未知')
                
                available_item = QTableWidgetItem(available_text)
                available_item.setFlags(available_item.flags() & ~Qt.ItemIsEditable)
                self.hosts_table.setItem(i, 4, available_item)
            
            # 更新状态
            self.status_label.setText(f"代理 {proxy_name} 下共有 {len(hosts)} 台主机")
            
            # 启用导出按钮
            self.export_btn.setEnabled(True)
            self.copy_btn.setEnabled(True)
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"查询主机失败: {str(e)}")
            logger.error(f"查询主机失败: {str(e)}")
            self.status_label.setText("查询失败")
    
    def filter_hosts(self, text):
        """过滤主机列表"""
        text = text.lower()
        for i in range(self.hosts_table.rowCount()):
            hostname = self.hosts_table.item(i, 1).text().lower()
            visible_name = self.hosts_table.item(i, 2).text().lower()
            
            self.hosts_table.setRowHidden(
                i, text and text not in hostname and text not in visible_name
            )
    
    def on_export(self):
        """导出主机列表到CSV"""
        if not self.hosts_data:
            QMessageBox.warning(self, "警告", "没有数据可以导出")
            return
        
        # 获取保存文件路径
        file_path, _ = QFileDialog.getSaveFileName(
            self,
            "导出CSV文件",
            "",
            "CSV 文件 (*.csv)"
        )
        
        if not file_path:
            return
        
        try:
            # 添加扩展名
            if not file_path.lower().endswith('.csv'):
                file_path += '.csv'
            
            # 获取代理名称
            proxy_name = self.proxy_combo.currentText()
            
            # 写入CSV
            with open(file_path, 'w', newline='', encoding='utf-8-sig') as f:
                writer = csv.writer(f)
                
                # 写入标题行
                writer.writerow(['代理', '主机ID', '主机名', '可见名称', '状态', '可用性'])
                
                # 写入数据
                for host in self.hosts_data:
                    status = "启用" if host.get('status', '1') == '0' else "禁用"
                    
                    available = host.get('available', '0')
                    available_text = {
                        '0': '未知',
                        '1': '可用',
                        '2': '不可用'
                    }.get(available, '未知')
                    
                    writer.writerow([
                        proxy_name,
                        host.get('hostid', ''),
                        host.get('host', ''),
                        host.get('name', ''),
                        status,
                        available_text
                    ])
            
            QMessageBox.information(self, "成功", f"数据已成功导出到:\n{file_path}")
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"导出失败: {str(e)}")
            logger.error(f"导出失败: {str(e)}")
    
    def on_copy_hostnames(self):
        """复制主机名称到剪贴板"""
        if not self.hosts_data:
            QMessageBox.warning(self, "警告", "没有数据可以复制")
            return
        
        try:
            # 提取主机名
            hostnames = [host.get('host', '') for host in self.hosts_data]
            
            # 过滤空主机名并用换行符连接
            text = '\n'.join(filter(None, hostnames))
            
            # 复制到剪贴板
            from PyQt5.QtGui import QClipboard
            from PyQt5.QtWidgets import QApplication
            clipboard = QApplication.clipboard()
            clipboard.setText(text)
            
            QMessageBox.information(self, "成功", f"已复制 {len(hostnames)} 个主机名到剪贴板")
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"复制失败: {str(e)}")
            logger.error(f"复制失败: {str(e)}") 